package web.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import entity.Extract;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import service.ExtractService;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

public class ChooseAction extends ActionSupport implements ModelDriven<Extract> {

    private ExtractService es;

    private Extract extract = new Extract();

    public String into() {
        //手机号码通过验证了
        HttpSession session = ServletActionContext.getRequest().getSession();
        //1.先从session中取extract对象
        Extract session_extract = (Extract) session.getAttribute("extract");
        if (session_extract == null) {
            //session中没有extract对象就使用接收到的extract对象,
            // 封装参数后,存到session中,和数据库中
//            System.out.println("提取码:"+extract.getExtract_code());
            if (extract.getExtract_code() == null || "".equals(extract.getExtract_code())) {
//                System.out.println("进入了if");
                String file_signal = UUID.randomUUID().toString().trim();
                extract.setFile_signal(file_signal);//生成对应的文件序列
                String file_signal_format = file_signal.replaceAll("-", "");
                String extract_code = "";
                for (int i = 0; i < 6; i++) {
                    int index = new Random().nextInt(file_signal_format.length() - 6);
                    extract_code = extract_code + file_signal_format.charAt(index);
                }
                extract.setExtract_code(extract_code);
//                System.out.println(extract);
                es.save(extract);
            } else {
//                System.out.println("进入了else");
                DetachedCriteria dc = DetachedCriteria.forClass(Extract.class);
                Map<String, String> map = new HashMap<String, String>();
                map.put("phone_num", extract.getPhone_num());
                map.put("extract_code", extract.getExtract_code());
                dc.add(Restrictions.allEq(map));
//                System.out.println("封装好了查询数据:" + map.toString());
                extract = es.getExtractByCondition(dc);
//                System.out.println("进行了离线查询,查询结果是:" + extract);

                if (extract == null) {
                    ServletActionContext.getRequest().setAttribute("notExtract",
                            "提取信息不存在!");
                    return ERROR;
                }
            }
            session.setAttribute("extract", extract);
        }
        //3.跳转到选择页面
        return "choose";
    }

    @Override
    public Extract getModel() {
        return extract;
    }

    public void setEs(ExtractService es) {
        this.es = es;
    }
}
